<!doctype html>
<html lang='en'>
<head>
  <meta charset='utf-8' />
  <title>聊天室</title>
  <link rel='stylesheet' href='/stylesheets/style.css'></link>
</head>
<body>
<div id='content'>
  <!-- 显示当前聊天室名称的div -->
  <div id='room'></div>
  <!-- 显示当前可用聊天室列表的div -->
  <div id='room-list'></div>
  <!-- 显示聊天消息的div -->
  <div id='messages'></div>
  
  <form id='send-form'>
    <!-- 用户用来输入聊天命令和消息的表单输入元素 -->
    <input id='send-message' />
    <input id='send-button' type='submit' value='发送' />
    
    <div id='help'>
      聊天命令: 
      <ul>
        <li>修改昵称: <code>/nick [你的名字]</code></li>
        <li>加入/创建房间: <code>/join [房间名称]</code></li> 
      </ul>
    </div>
  </form>
</div>
<script src='/socket.io/socket.io.js' type='text/javascript'></script>
<script src='http://libs.baidu.com/jquery/1.11.1/jquery.min.js' type='text/javascript'></script>
<script src='/javascripts/chat.js' type='text/javascript'></script>
<script src='/javascripts/chat_ui.js' type='text/javascript'></script>
<script type='text/javascript'>
  var socket = io.connect();
  
  $(document).ready(function() {
    var chatApp = new Chat(socket);

    socket.on('nameResult', function(result) { // 显示更名尝试的结果
      var message;
      if (result.success) {
        message = '你现在的名字是' + result.name + '.';
      } else {
        message = result.message;
      }
      $('#messages').append(divSystemContentElement(message));
    });

    socket.on('joinResult', function(result) { // 显示房间变更结果
      $('#room').text(result.room);
      $('#messages').append(divSystemContentElement('变更房间'));
    });

    socket.on('message', function(message) { // 显示接收到的消息
      var newElement = $('<div></div>').text(message.text);
      $('#messages').append(newElement);
    });

    socket.on('rooms', function(rooms) { // 显示可用房间列表
      $('#room-list').empty();
      for (var room in rooms) {
        room = room.substring(1, room.length);
        if (room != '') {
          $('#room-list').append(divEscapedContentElement(room));
        }
      }
      $('#room-list div').click(function() { // 点击房间名可以换到那个房间中
        chatApp.processCommand('/join ' + $(this).text());
        $('#send-message').focus();
      });
    });

    setInterval(function() { // 定期请求可用房间列表
      socket.emit('rooms');
    }, 1000);

    $('#send-message').focus();

    $('#send-form').submit(function() { // 提交表单可以发送聊天消息
      processUserInput(chatApp, socket);
      return false;
    });

  });
</script>
</body>
</html>
